import { Image, Message, Upload } from '@arco-design/web-react';
import { RequestOptions, UploadItem, UploadStatus } from '@arco-design/web-react/es/Upload';
import { apiUploadFile } from '@src/page/api/api';

import { imageFileType } from '@src/utils/defaultData';
import { useEffect, useState } from 'react';
interface Props {
  values?: string[];
  limit?: number;
  size?: number;
  disabled?: boolean;
  fileSize?: number;
  onChange?: (values: string[]) => void;
}
// 多个文件同时上传会被防抖拦截，加个参数，防止拦截
let uploadNum = 0;
export default function UploadImg({ limit = 1, size, onChange, fileSize, disabled, values }: Props) {
  const [picList, setPicList] = useState<UploadItem[]>([]);

  useEffect(() => {
    let pics = (values ?? []).map((i, idx) => ({
      uid: idx.toString(),
      name: 'img' + idx,
      url: i as string,
      status: 'done' as UploadStatus,
    }));
    setPicList(pics);
  }, [values]); // eslint-disable-line

  function handleRemove(item: UploadItem) {
    if (disabled) return;
    let _values = picList.filter((i) => i.uid !== item.uid);
    setPicList(_values);
  }
  // 验证文件格式
  function isAcceptFile(file?: File) {
    if (fileSize && file!.size / 1024 / 1024 > fileSize) {
      Message.error(`上传${fileSize}M以内的图片`);
      return false;
    }
    if (file) {
      const fileExtension: string = (file.name.indexOf('.') > -1 ? file.name.split('.').pop() : '') ?? '';
      if (imageFileType.includes(fileExtension)) return true;
      return false;
    }
    return !!file;
  }

  // 上传
  async function handleUpload(options: RequestOptions) {
    // TODO: 同时上传多张图片会被axios拦截，需要做处理
    if (!isAcceptFile(options.file)) {
      return;
    }
    try {
      uploadNum++;
      let res = await apiUploadFile(
        options.file,
        (l, t) => {
          let procress = (l / t) * 100;
          procress = procress > 100 ? 100 : procress;
          options.onProgress(procress);
        },
        uploadNum
      );
      let data = res.data;
      if (data.code === 200) {
        options.onSuccess(data);
      } else {
        options.onError(data);
      }
    } catch (e) {
      options.onError();
    }
  }

  // 文件变化
  async function handleChange(fl: UploadItem[], file: UploadItem) {
    if (disabled) return;
    let map: { [x: string]: UploadItem } = {};
    let _doneList: string[] = [];
    for (let item of fl) {
      if (item.status === 'done') {
        if (!item.url) {
          // @ts-ignore
          item.url = item.response!.data.url;
        }
        if (!!item.url) {
          _doneList.push(item.url!);
        }
      }
      map[item.uid] = item;
    }
    let _list = Object.values(map);
    setPicList(_list);
    if (_list.length === _doneList.length) {
      onChange?.(_doneList);
    }
  }

  if (disabled) {
    return (
      <div className="d-flex-r">
        {(values ?? []).map((i, idx) => (
          <Image className="mr-5 mb-5" key={i + idx} src={i} width={size ?? 60} height={size ?? 60} />
        ))}
      </div>
    );
  }

  return (
    <Upload
      disabled={disabled}
      accept="image/*"
      multiple={limit > 1}
      limit={limit}
      imagePreview
      fileList={picList}
      customRequest={handleUpload}
      listType="picture-card"
      onChange={handleChange}
      onRemove={handleRemove}
    />
  );
}
